/**
 * 前端权限控制工具函数
 */

import { apiClients } from '@/services/apiClient';

// 权限缓存接口
interface PermissionCache {
  permissions: string[];
  roles: string[];
  timestamp: number;
  ttl: number; // 缓存时间（毫秒）
}

// 权限缓存管理
class PermissionManager {
  private static instance: PermissionManager;
  private cache: PermissionCache | null = null;
  private readonly CACHE_KEY = 'user_permissions_cache';
  private readonly DEFAULT_TTL = 30 * 60 * 1000; // 30分钟

  static getInstance(): PermissionManager {
    if (!PermissionManager.instance) {
      PermissionManager.instance = new PermissionManager();
    }
    return PermissionManager.instance;
  }

  /**
   * 获取用户权限（带缓存）
   */
  async getUserPermissions(): Promise<string[]> {
    // 检查缓存是否有效
    if (this.isCacheValid()) {
      return this.cache!.permissions;
    }

    try {
      // 从后端获取权限
      const permissions = await this.fetchPermissionsFromAPI();
      
      // 更新缓存
      this.updateCache(permissions, []);
      
      return permissions;
    } catch (error) {
      console.error('获取用户权限失败:', error);
      return [];
    }
  }

  /**
   * 获取用户角色（带缓存）
   */
  async getUserRoles(): Promise<string[]> {
    // 检查缓存是否有效
    if (this.isCacheValid()) {
      return this.cache!.roles;
    }

    try {
      // 从后端获取角色
      const roles = await this.fetchRolesFromAPI();
      
      // 更新缓存
      this.updateCache([], roles);
      
      return roles;
    } catch (error) {
      console.error('获取用户角色失败:', error);
      return [];
    }
  }

  /**
   * 检查用户是否具有指定权限
   */
  async hasPermission(permission: string): Promise<boolean> {
    const permissions = await this.getUserPermissions();
    return permissions.includes(permission);
  }

  /**
   * 检查用户是否具有任一权限
   */
  async hasAnyPermission(permissions: string[]): Promise<boolean> {
    const userPermissions = await this.getUserPermissions();
    return permissions.some(permission => userPermissions.includes(permission));
  }

  /**
   * 检查用户是否具有所有权限
   */
  async hasAllPermissions(permissions: string[]): Promise<boolean> {
    const userPermissions = await this.getUserPermissions();
    return permissions.every(permission => userPermissions.includes(permission));
  }

  /**
   * 检查用户是否具有指定角色
   */
  async hasRole(role: string): Promise<boolean> {
    const roles = await this.getUserRoles();
    return roles.includes(role);
  }

  /**
   * 清除权限缓存
   */
  clearCache(): void {
    this.cache = null;
    localStorage.removeItem(this.CACHE_KEY);
  }

  /**
   * 从API获取权限
   */
  private async fetchPermissionsFromAPI(): Promise<string[]> {
    try {
      const response = await apiClients.users.usersPermissionsRetrieve();
      const permissionExtensions = response.data || [];

      // 将权限扩展转换为权限代码名数组
      return permissionExtensions.map(ext => {
        if (ext.permission_codename && ext.permission_app_label) {
          return `${ext.permission_app_label}.${ext.permission_codename}`;
        }
        return '';
      }).filter(Boolean);
    } catch (error) {
      console.error('从API获取权限失败:', error);
      return [];
    }
  }

  /**
   * 从API获取角色
   */
  private async fetchRolesFromAPI(): Promise<string[]> {
    try {
      const response = await apiClients.users.usersRolesRetrieve();
      return response.data || [];
    } catch (error) {
      console.error('从API获取角色失败:', error);
      return [];
    }
  }

  /**
   * 检查缓存是否有效
   */
  private isCacheValid(): boolean {
    if (!this.cache) {
      // 尝试从localStorage恢复缓存
      const cached = localStorage.getItem(this.CACHE_KEY);
      if (cached) {
        try {
          this.cache = JSON.parse(cached);
        } catch (error) {
          console.error('解析权限缓存失败:', error);
          return false;
        }
      }
    }

    if (!this.cache) {
      return false;
    }

    // 检查是否过期
    const now = Date.now();
    return (now - this.cache.timestamp) < this.cache.ttl;
  }

  /**
   * 更新缓存
   */
  private updateCache(permissions: string[], roles: string[]): void {
    this.cache = {
      permissions,
      roles,
      timestamp: Date.now(),
      ttl: this.DEFAULT_TTL,
    };

    // 保存到localStorage
    localStorage.setItem(this.CACHE_KEY, JSON.stringify(this.cache));
  }
}

// 导出单例实例
const permissionManager = PermissionManager.getInstance();

// 导出便捷函数
export const hasPermission = (permission: string): Promise<boolean> => {
  return permissionManager.hasPermission(permission);
};

export const hasAnyPermission = (permissions: string[]): Promise<boolean> => {
  return permissionManager.hasAnyPermission(permissions);
};

export const hasAllPermissions = (permissions: string[]): Promise<boolean> => {
  return permissionManager.hasAllPermissions(permissions);
};

export const hasRole = (role: string): Promise<boolean> => {
  return permissionManager.hasRole(role);
};

export const getUserPermissions = (): Promise<string[]> => {
  return permissionManager.getUserPermissions();
};

export const getUserRoles = (): Promise<string[]> => {
  return permissionManager.getUserRoles();
};

export const clearPermissionCache = (): void => {
  permissionManager.clearCache();
};

// 权限常量定义
export const PERMISSIONS = {
  // 用户管理权限
  USER: {
    VIEW: 'authentication.view_user',
    ADD: 'authentication.add_user',
    CHANGE: 'authentication.change_user',
    DELETE: 'authentication.delete_user',
  },
  
  // 权限管理权限
  PERMISSION: {
    VIEW_CATEGORY: 'permissions.view_permissioncategory',
    ADD_CATEGORY: 'permissions.add_permissioncategory',
    CHANGE_CATEGORY: 'permissions.change_permissioncategory',
    DELETE_CATEGORY: 'permissions.delete_permissioncategory',
    
    VIEW_PERMISSION: 'permissions.view_permissionextension',
    ADD_PERMISSION: 'permissions.add_permissionextension',
    CHANGE_PERMISSION: 'permissions.change_permissionextension',
    DELETE_PERMISSION: 'permissions.delete_permissionextension',
    
    VIEW_ROLE: 'permissions.view_roleextension',
    ADD_ROLE: 'permissions.add_roleextension',
    CHANGE_ROLE: 'permissions.change_roleextension',
    DELETE_ROLE: 'permissions.delete_roleextension',
    
    VIEW_USER_ROLE: 'permissions.view_userroleassignment',
    ADD_USER_ROLE: 'permissions.add_userroleassignment',
    CHANGE_USER_ROLE: 'permissions.change_userroleassignment',
    DELETE_USER_ROLE: 'permissions.delete_userroleassignment',
  },

  // AI对话平台权限
  AI_CHAT: {
    // AI提供商权限
    VIEW_AI_PROVIDER: 'ai_chat.view_aiprovider',
    ADD_AI_PROVIDER: 'ai_chat.add_aiprovider',
    CHANGE_AI_PROVIDER: 'ai_chat.change_aiprovider',
    DELETE_AI_PROVIDER: 'ai_chat.delete_aiprovider',

    // AI模型权限
    VIEW_AI_MODEL: 'ai_chat.view_aimodel',
    ADD_AI_MODEL: 'ai_chat.add_aimodel',
    CHANGE_AI_MODEL: 'ai_chat.change_aimodel',
    DELETE_AI_MODEL: 'ai_chat.delete_aimodel',

    // AI角色权限
    VIEW_AI_ROLE: 'ai_chat.view_airole',
    ADD_AI_ROLE: 'ai_chat.add_airole',
    CHANGE_AI_ROLE: 'ai_chat.change_airole',
    DELETE_AI_ROLE: 'ai_chat.delete_airole',

    // AI对话权限
    VIEW_AI_CONVERSATION: 'ai_chat.view_aiconversation',
    ADD_AI_CONVERSATION: 'ai_chat.add_aiconversation',
    CHANGE_AI_CONVERSATION: 'ai_chat.change_aiconversation',
    DELETE_AI_CONVERSATION: 'ai_chat.delete_aiconversation',

    // 消息模板权限
    VIEW_MESSAGE_TEMPLATE: 'ai_chat.view_messagetemplate',
    ADD_MESSAGE_TEMPLATE: 'ai_chat.add_messagetemplate',
    CHANGE_MESSAGE_TEMPLATE: 'ai_chat.change_messagetemplate',
    DELETE_MESSAGE_TEMPLATE: 'ai_chat.delete_messagetemplate',

    // Token使用统计权限
    VIEW_TOKEN_USAGE: 'ai_chat.view_tokenusagelog',

    // 用户收藏权限
    VIEW_USER_FAVORITE: 'ai_chat.view_userfavorite',
    ADD_USER_FAVORITE: 'ai_chat.add_userfavorite',
    CHANGE_USER_FAVORITE: 'ai_chat.change_userfavorite',
    DELETE_USER_FAVORITE: 'ai_chat.delete_userfavorite',
  },
} as const;

// 角色常量定义
export const ROLES = {
  SUPER_ADMIN: 'super_admin',
  ADMIN: 'admin',
  USER_MANAGER: 'user_manager',
  PERMISSION_MANAGER: 'permission_manager',
  VIEWER: 'viewer',
} as const;
